﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using DAL;
using System.Collections;
using Facade.Excel;

namespace PeisongWeb.admin
{
    public partial class payableList : adminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (hasPermission("GC", 1))
                {
                    drpBind();
                    rptBind();
                    showCollect();
                }
                else
                {
                    Library.Script.ClientMsgUrl("没有权限！", "index.aspx");
                    return;
                }
                
            }
        }
        void drpBind()
        {
            //ddl_Status.DataSource = logic.sysCode.paymentStatus();
            ddl_Status.DataSource = logic.sysCode.listWithPayStatus("2");
            ddl_Status.DataBind();
            ddl_Status.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));

            ddl_Paymethod.DataSource = logic.sysCode.payMethodList();
            ddl_Paymethod.DataBind();
            ddl_Paymethod.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));

            //drp_Status.DataSource = logic.sysCode.orderStatus();
            //drp_Status.DataBind();
            //drp_Status.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));
        }
        void rptBind()
        {
            StringBuilder where = new StringBuilder();
            where.Append("type='2'");
            if (txt_companyName.Text.Trim() != "")
                where.AppendFormat(" and companyName like '%{0}%'", txt_companyName.Text.Trim());
            if (txt_CompanyNo.Text.Trim() != "")
                where.AppendFormat(" and companyNo like '%{0}%'", txt_CompanyNo.Text.Trim());
            if (ddl_Status.SelectedValue != "")
                where.AppendFormat(" and status = '{0}'", ddl_Status.SelectedValue.Trim());
            if (ddl_Paymethod.SelectedValue != "")
                where.AppendFormat(" and payMethod = '{0}'", ddl_Paymethod.SelectedValue.Trim());
            if (ext_StartInputDt.SelectedDate != DateTime.MinValue && ext_StartInputDt.Value.ToString() != "")
                where.AppendFormat(" and datediff(day,[startDt],'{0}')<=0", ext_StartInputDt.Value.ToString());
            if (ext_EndInputDt.SelectedDate != DateTime.MinValue && ext_EndInputDt.Value.ToString() != "")
                where.AppendFormat(" and datediff(day,[endDt],'{0}')>=0", ext_EndInputDt.Value.ToString());

            DataSet ds = logic.paymentHistory.select(where.ToString(), "payId desc", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
            AspNetPager1.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            rpt_list.DataSource = ds.Tables[1];
            rpt_list.DataBind();
        }
        protected void rpt_list_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "upadateStatus")
            {
                int payId = Convert.ToInt32(e.CommandArgument);

                PaymentHistoryEntity phe = new PaymentHistoryEntity();
                phe.AdminId = logic.sysAdmin.AdminID;
                phe.Status = "2"; //确认付款
                phe.PayId = payId;
                logic.paymentHistory.update(phe);
        
                rptBind();

                Library.Script.ClientMsg("已经成功更新！");
            }
            else if (e.CommandName == "Details")
            {
                AspNetPager2.CurrentPageIndex = 1;
                int payId = Convert.ToInt32(e.CommandArgument);
                PaymentHistoryEntity _phe = logic.paymentHistory.getByPayId(payId);
                hid_companyId.Value = _phe.CompanyId.ToString();
                hid_startDt.Value = _phe.StartDt.ToString();
                hid_endDt.Value = _phe.EndDt.ToString();
                hid_PayId.Value = payId.ToString();
                rptOrderItemBind(payId);
                orderItem.Show();
            }
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            rptBind();
        }
        protected void lbtn_Search_Click(object sender, EventArgs e)
        {
            rptBind();
            showCollect();
        }

        protected void AspNetPager2_PageChanged(object sender, EventArgs e)
        {
            int payId = Convert.ToInt32(hid_PayId.Value);
            rptOrderItemBind(payId);
        }
        void rptOrderItemBind(int payId)
        {
            int company = Convert.ToInt32(hid_companyId.Value);
            string startDt = hid_startDt.Value;
            string endDt = hid_endDt.Value;
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("sellerId={0} ", company);
            sb.AppendFormat(" and datediff(day,[updateStatusdt],'{0}')<=0", startDt);
            sb.AppendFormat(" and datediff(day,[updateStatusdt],'{0}')>=0", endDt);
            sb.AppendFormat(" and payid={0} ", payId);
            if (txt_orderNo.Text.Trim() != "")
                sb.AppendFormat("and orderno='{0}'", txt_orderNo.Text.Trim());
            //if (drp_Status.SelectedItem.Value != "")
            //    sb.AppendFormat(" and [status]={0}", drp_Status.SelectedItem.Value);
            DataSet ds = logic.orderItem.listWithOrder(sb.ToString(), "oiid", AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
            AspNetPager2.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            rpt_orderItem.DataSource = ds.Tables[1];
            rpt_orderItem.DataBind();
            //txt_sellerName.Text = ds.Tables[1].Rows[1]["sellerName"].ToString()+"所供应的商品的订单信息";
            rpt_orderItemBind();
        }

        protected void lbn_select_Click(object sender, EventArgs e)
        {
            int payId = Convert.ToInt32(hid_PayId.Value);
            rptOrderItemBind(payId);
        }


        private DataSet orderItemByWhere()
        {
            int company = Convert.ToInt32(hid_companyId.Value);
            string startDt = hid_startDt.Value;
            string endDt = hid_endDt.Value;
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("sellerId={0} ", company);
            sb.AppendFormat(" and datediff(day,[updateStatusdt],'{0}')<=0", startDt);
            sb.AppendFormat(" and datediff(day,[updateStatusdt],'{0}')>=0", endDt);
            int payid = Convert.ToInt32(hid_PayId.Value);
            sb.AppendFormat(" and payid={0} ", payid);
            if (txt_orderNo.Text.Trim() != "")
                sb.AppendFormat("and orderno='{0}'", txt_orderNo.Text.Trim()); ;
            DataSet ds = logic.orderItem.listwithPayables(sb.ToString());
            return ds;
        }
        protected void lbn_Import_Click(object sender, EventArgs e)
        {
            DataSet ds = orderItemByWhere();
            DataTable dt = ds.Tables[0]; 
            dt.Columns["proName"].ColumnName = "商品";
            dt.Columns["quantity"].ColumnName = "数量";
            dt.Columns["sellerPrice"].ColumnName = "供应价";
            dt.Columns["unit"].ColumnName = "单位";
            dt.Columns["sellerAmount"].ColumnName = "小计";
            dt.Columns["orderNo"].ColumnName = "订单号";
            dt.Columns["statusName"].ColumnName = "订单状态";
            dt.Columns["updateStatusdt"].ColumnName = "成功日期";
            dt.Columns["rbno"].ColumnName = "提货单号";

            ExportFacade facadeInstance = new ExportFacade();
            Dictionary<int, FormatStyle> formatOptions = new Dictionary<int, FormatStyle>();
            formatOptions.Add(1, FormatStyle.ToFix2);
            formatOptions.Add(2, FormatStyle.ToFix2);
            formatOptions.Add(4, FormatStyle.ToFix2);

            facadeInstance.ExportByWeb(dt,"订单数据","订单数据.xls",formatOptions,"订单数据");
        }

        private void showCollect()
        {
            int companyId = 0;
            DateTime? startDt = null;
            DateTime? endDt = null;
            if (ext_StartInputDt.SelectedDate != DateTime.MinValue) startDt = ext_StartInputDt.SelectedDate;
            if (ext_EndInputDt.SelectedDate != DateTime.MinValue) endDt = ext_EndInputDt.SelectedDate;

            string companyName = txt_companyName.Text.Trim();
            string companyNo = txt_CompanyNo.Text.Trim();
            string paymethod = ddl_Paymethod.SelectedValue.Trim();

            DataRow dr = logic.paymentHistory.listWithCollectByFinancial(companyId, startDt, endDt, companyName, companyNo, paymethod, "2").Rows[0];
            lit_orderNum.Text = string.Format("{0:N}", dr["orderNum"]);
            lit_payMoney.Text = string.Format("{0:N}", dr["payMoney"]);
            lit_notPayMoney.Text = string.Format("{0:N}", dr["notPayMoney"]);
            lit_total.Text = string.Format("{0:N}", dr["orderAmount"]);
        }

        private void rpt_orderItemBind()
        {  
            //foreach (RepeaterItem item in rpt_orderItem.Items)
            //{
            //    if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
            //    {
            //        Literal lbl = item.FindControl("lblAmount") as Literal;

            //        if (lbl != null)
            //        {
            //            totalPrice += decimal.Parse(lbl.Text);
            //        }
            //    }
            //}
            DataTable dt = orderItemByWhere().Tables[2];
            lbl_Total.Text = string.Format("{0:F2}",dt.Rows[0]["sellerTotal"]);
        }

        /// <summary>
        /// 预览应付款
        /// </summary>
        private void rptPreview_Bind()
        {
            StringBuilder where = new StringBuilder();
            where.Append("1=1");
            if (txt_company_view.Text.Trim() != "")
                where.AppendFormat(" and sellerName like '%{0}%'", txt_company_view.Text.Trim());
            if (ext_startDt_view.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[updateStatusdt],'{0}')<=0", ext_startDt_view.Value.ToString());
            if (ext_endDt_view.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[updateStatusdt],'{0}')>=0", ext_endDt_view.Value.ToString());


            DataSet ds = logic.orderItem.listWithPreview(where.ToString(), "oiid", AspNetPager_view.PageSize, AspNetPager_view.CurrentPageIndex);
            AspNetPager_view.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            rpt_Preview.DataSource = ds.Tables[1];
            rpt_Preview.DataBind();

            DataTable dt = logic.paymentHistory.listWithPreview(where.ToString());
            rpt_PreviewPayable.DataSource = dt;
            rpt_PreviewPayable.DataBind();
            win_Preview.Show();
        }

        protected void btn_Preview_Click(object sender, EventArgs e)
        {
            AspNetPager_view.CurrentPageIndex = 1;
            rptPreview_Bind();
        }

        protected void AspNetPager_view_PageChanged(object sender, EventArgs e)
        {
            rptPreview_Bind();
        }

        protected void btn_create_click(object sender, EventArgs e)
        {
            StringBuilder where = new StringBuilder();
            where.Append("1=1");
            if (txt_company_view.Text.Trim() != "")
                where.AppendFormat(" and sellerName like '%{0}%'", txt_company_view.Text.Trim());

            if (ext_startDt_view.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[updateStatusdt],'{0}')<=0", ext_startDt_view.SelectedDate);
            if (ext_endDt_view.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[updateStatusdt],'{0}')>=0", ext_endDt_view.SelectedDate);

            DateTime? startDt = null;
            DateTime? endDt = null;

            if (ext_startDt_view.SelectedDate!=DateTime.MinValue)
            {
                startDt = ext_startDt_view.SelectedDate;
            }
            if (ext_endDt_view.SelectedDate!=DateTime.MinValue)
            {
                endDt = ext_endDt_view.SelectedDate;
            }

            int payId = logic.paymentHistory.insertPayableByFinance(where.ToString(),startDt,endDt);
            if (payId > 0)
            {
                Library.Script.ClientMsg("当前预览的应付款生成成功！");
            }
            else
            {
                Library.Script.ClientMsg("对不起，当前没有可以生成的应付款，请仔细核对！");
            }
            rptBind();
        }
    }
}
